from datetime import datetime, timedelta

from flask import request, Blueprint

from app import db
from app.models.book import Book
from app.models.book_tag import BookTag
from app.models.borrow_record import BorrowRecord
from app.models.parent_tag import ParentTag
from app.models.qrcode import Qrcode
from app.models.reader_book import ReaderBook
from app.models.tag import Tag
from app.utils.transform import row_to_dict
from app.utils.xuehuaid import IdWorker
from app.models.book_chapter import BookChapter

# 测试是否连接成功
# with app.app_context():
#     with db.engine.connect() as conn:
#         rs = conn.execute(text("select 1"))
#         print(rs.fetchone())  # (1,)


unorganized = Blueprint("unorganized", __name__)


@unorganized.route("/qrcode/<userid>", methods=["POST"])
def get_qrcode(userid):
    data = ""

    # 创建一个QRCode对象
    import qrcode
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )

    # 添加数据到QRCode对象
    qr.add_data(data)
    qr.make(fit=True)

    # 创建一个PIL Image对象
    img = qr.make_image(fill='black', back_color='white')
    from io import BytesIO
    buffered = BytesIO()
    img.save(buffered, format="PNG")

    # 将BytesIO流设置为文件的开头，以便Flask可以读取
    buffered.seek(0)
    qr_image_bytes = buffered.getvalue()
    new_qr_code = Qrcode(user_id=userid, qrcode=qr_image_bytes)  # some_user_id 是你要关联的用户的ID
    db.session.add(new_qr_code)  # 添加到会话
    db.session.commit()  # 提交会话以保存到数据库

    # 使用send_file发送图像
    from flask import send_file
    return send_file(
        buffered,
        mimetype='image/png',
        as_attachment=False,  # 如果作为附件发送，设置为True
        download_name='qrcode.png'  # 如果作为附件发送，指定文件名
    )


@unorganized.route("/qrcode/<userid>", methods=["GET"])
def get_qr_code(userid):
    qr_code_record = db.session.query(Qrcode).filter_by(user_id=userid).first()
    qrcode_data = qr_code_record.qrcode
    from io import BytesIO
    image_io = BytesIO(qrcode_data)

    # 将BytesIO对象设置为文件的开头
    image_io.seek(0)

    # 使用send_file发送图像给前端
    from flask import send_file
    return send_file(
        image_io,
        mimetype='image/png',
        as_attachment=False,  # 如果作为附件发送，设置为True
        download_name='qrcode.png'  # 如果作为附件发送，指定文件名
    )


@unorganized.route("/borrowings", methods=["POST"])
def borrowings():
    worker = IdWorker(1, 2, 0)
    recordId = worker.get_id()
    bookId = request.get_json()['book_id']
    userId = request.get_json()['userid']
    isAdministrator = request.get_json()['isAdministrator']
    seven_days = timedelta(days=7)
    is_return = False
    borrowRecord = BorrowRecord(book_id=bookId, user_id=userId, record_id=recordId, borrow_date=datetime.now(),
                                return_date=datetime.now() + seven_days, is_return=is_return, is_get=isAdministrator)
    db.session.add(borrowRecord)
    db.session.commit()
    return '', 204


@unorganized.route("/borrowings", methods=["PUT"])
def return_books():
    bookId = request.get_json()['book_id']
    record = db.session.query(BorrowRecord).filter(BorrowRecord.book_id == bookId,
                                                   BorrowRecord.is_return == False).first()
    record.gmt_modified = datetime.now()
    record.is_return = True
    borrowDate = record.borrow_date
    returnDate = datetime.now()
    delta = returnDate - borrowDate
    days = delta.days
    db.session.commit()
    if days > 7:
        return {"message": "还书成功！借阅天数： " + str(days) + "  需要收费：" + str((days - 7) * 0.1)}
    else:
        return {"message": "还书成功！！！" }


@unorganized.route('/borrowings', methods=['GET'])
def getBorrowings1():
    borrows = db.session.query(BorrowRecord).all()
    results = []
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    for borrow in borrows:
        result = row_to_dict(borrow)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    borrows = results[start_index:end_index]
    for borrow in borrows:
        book = db.session.query(Book).filter(Book.book_id == borrow['book_id']).first()
        borrow["book_name"] = book.book_title
    return {"num": len(results), "data": borrows}


@unorganized.route('/chapters/<bookId>', methods=['GET'])
def getChapters(bookId):
    bookId = int(bookId)
    chapters = db.session.query(BookChapter).filter(BookChapter.book_id == bookId).all()
    results = []
    for chapter in chapters:
        result = row_to_dict(chapter)
        results.append(result)
    return {"data": results}


@unorganized.route('/chapters/<bookName>/<num>', methods=['GET'])
def getChaptersByNum(bookName, num):
    secret_id = 'AKIDtm0AC8xZ4Um3JYfYEwbIwb9QZdcPOF22'
    secret_key = '5DHVozDUbnQyNcqxwtneMpFbuR2ZAi3T'
    region = 'ap-nanjing'  # 替换为你的region
    token = None  # 使用临时密钥需要传入Token，默认为空,可不填

    # 获取配置对象
    from qcloud_cos import CosConfig
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)
    # 初始化cos客户端
    from qcloud_cos import CosS3Client
    client = CosS3Client(config)

    # 指定要下载的COS文件路径和存储桶名称
    bucket_name = '511-1324396731'  # 替换为你的存储桶名称
    cos_path = '/novel/' + bookName + '/' + num + '.txt'  # 替换为你要下载的文件的COS路径

    # 调用get_object接口下载文件
    response = client.get_object(
        Bucket=bucket_name,
        Key=cos_path,
    )

    # 从响应中获取文件内容
    body = response['Body']
    chunks = []

    # 分块读取内容，这里我们假设每块大小为 1024 字节（可以根据需要调整）
    chunk = body.read(1024)
    while chunk:
        chunks.append(chunk)
        chunk = body.read(1024)

        # 将内容块合并为一个完整的 bytes 对象
    content = b''.join(chunks)

    # 将bytes转换为字符串（如果文件是文本文件）
    text_content = content.decode('utf-8')  # 假设文件是UTF-8编码
    return {"content": text_content}


@unorganized.route('/borrowings/<bookId>/<userId>', methods=['GET'])
def addBorrowings(bookId, userId):
    bookId = int(bookId)
    userId = int(userId)
    worker = IdWorker(1, 2, 0)
    recordId = worker.get_id()
    seven_days = timedelta(days=7)
    is_return = False
    borrowRecord = BorrowRecord(book_id=bookId, user_id=userId, record_id=recordId, borrow_date=datetime.now(),
                                return_date=datetime.now() + seven_days, is_return=is_return, is_get=False)
    db.session.add(borrowRecord)
    db.session.commit()
    data = bookId

    # 创建一个QRCode对象
    import qrcode
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )

    # 添加数据到QRCode对象
    qr.add_data(data)
    qr.make(fit=True)

    # 创建一个PIL Image对象
    img = qr.make_image(fill='black', back_color='white')
    from io import BytesIO
    buffered = BytesIO()
    img.save(buffered, format="PNG")

    # 将BytesIO流设置为文件的开头，以便Flask可以读取
    buffered.seek(0)
    buffered.getvalue()

    # 使用send_file发送图像
    from flask import send_file
    return send_file(
        buffered,
        mimetype='image/png',
        as_attachment=False,  # 如果作为附件发送，设置为True
        download_name='qrcode.png'  # 如果作为附件发送，指定文件名
    )


@unorganized.route("/administrators/borrowings", methods=["PUT"])
def confirmBorrowings():
    bookId = request.get_json()['book_id']
    borrow = db.session.query(BorrowRecord).filter(BorrowRecord.book_id == bookId,
                                                   BorrowRecord.is_get == False).first()
    borrow.is_get = True
    db.session.commit()
    return {"message": "success"}


@unorganized.route('/borrowings/<userid>', methods=['GET'])
def getBorrowings(userid):
    userid = int(userid)
    borrows = db.session.query(BorrowRecord).filter(BorrowRecord.user_id == userid).all()
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    results = []
    for borrow in borrows:
        result = row_to_dict(borrow)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    borrows = results[start_index:end_index]
    for borrow in borrows:
        book = db.session.query(Book).filter(Book.book_id == borrow['book_id']).first()
        borrow["book_name"] = book.book_title
    return {"num": len(results), "data": borrows}


@unorganized.route("/parenttags", methods=["GET"])
def get_parent_tags():
    tags = db.session.query(ParentTag).all()
    results = []
    for tag in tags:
        result = row_to_dict(tag)
        results.append(result)
    return {"data": results}


@unorganized.route('/allBooks', methods=['PUT'])
def deleteAllBooks():
    allBooks = request.get_json()['books']
    for book in allBooks:
        book1 = db.session.query(Book).filter(Book.book_id == book).first()
        book1.stock = 0
        db.session.commit()
    return {"msg": "success"}


@unorganized.route("/parenttags", methods=["POST"])
def add_parent_tags():
    tag = request.get_json()['tag']
    tags = ParentTag(tag_name=tag)
    db.session.add(tags)
    db.session.commit()
    return '', 204


@unorganized.route("/tags", methods=["POST"])
def add_tags():
    tagName = request.get_json()['tagName']
    parentTagId = request.get_json()['parentTagId']
    tags = Tag(tag_name=tagName, parent_tag_id=parentTagId)
    db.session.add(tags)
    db.session.commit()
    return '', 204


@unorganized.route("/tags/<parentTagId>", methods=["GET"])
def get_tags(parentTagId):
    tags = db.session.query(Tag).filter(Tag.parent_tag_id == parentTagId).all()
    results = []
    for tag in tags:
        result = row_to_dict(tag)
        results.append(result)
    return {"data": results}


@unorganized.route("/readerborrowrecords", methods=["POST"])
def add_reader_borrow_records():
    worker = IdWorker(1, 2, 0)
    bookId = worker.get_id()
    bookTitle = request.get_json()['bookTitle']
    author = request.get_json()['author']
    bookISBN = request.get_json()['bookISBN']
    publishingHouse = request.get_json()['publishingHouse']
    source=request.get_json()['source']
    description = request.get_json()['description']
    book = Book(book_id=bookId, book_title=bookTitle, author=author, bookISBN=bookISBN,
                publishing_house=publishingHouse,
                gmt_create=datetime.now(),
                gmt_modified=datetime.now(),
                source=source,
                stock=1,
                description=description,
                is_user_book=False)
    db.session.add(book)
    tags = request.get_json()['childTagId']
    for tag in tags:
        bookTag = BookTag(book_id=bookId, tag_id=tag)
        db.session.add(bookTag)
    userId = request.get_json()['userId']
    readerBook = ReaderBook(user_id=userId, book_id=bookId)
    db.session.add(readerBook)
    db.session.commit()
    return {"message": "success"}

@unorganized.route('/readerborrowrecords/<userId>', methods=['GET'])
def getReaderBorrowRecords(userId):
    users = db.session.query(ReaderBook).filter(ReaderBook.user_id == userId).all()
    books=[]
    for user in users:
        book = db.session.query(Book).filter(Book.book_id == user.book_id, Book.stock == 1).first()
        books.append(book)
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    books = results[start_index:end_index]
    for book in books:
        bookTag1 = db.session.query(BookTag).join(Book, Book.book_id == BookTag.book_id).filter(
            BookTag.book_id == book["book_id"]).all()
        result1 = []
        for tag in bookTag1:
            Tag1 = db.session.query(Tag).filter(Tag.tag_id == tag.tag_id).first()
            parentTagId = Tag1.parent_tag_id
            parentTagName = db.session.query(ParentTag).filter(ParentTag.tag_id == parentTagId).first().tag_name
            result = row_to_dict(Tag1)
            result["parent_tag_name"] = parentTagName
            result1.append(result)
        book["tag"] = (result1)
    return {"num": len(results), "data": books}